import React, { useState, useEffect } from "react";
import "./ScheduleList.css";

export default function ScheduleList() {
  const [schedules, setSchedules] = useState([]);
  const [movies, setMovies] = useState({});
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  // 获取排片列表
  useEffect(() => {
    Promise.all([
      // 获取排片数据
      fetch("http://localhost:8080/api/schedules").then((response) => {
        if (!response.ok) {
          throw new Error("获取排片列表失败");
        }
        return response.json();
      }),
      // 获取电影数据，用于匹配movie_id和电影名称
      fetch("http://localhost:8080/api/movies").then((response) => {
        if (!response.ok) {
          throw new Error("获取电影列表失败");
        }
        return response.json();
      }),
    ])
      .then(([scheduleData, movieData]) => {
        // 将电影数据转换为对象，方便通过movie_id查找
        const movieMap = {};
        movieData.forEach((movie) => {
          movieMap[movie.id] = movie.title;
        });

        setSchedules(scheduleData);
        setMovies(movieMap);
        setLoading(false);
      })
      .catch((error) => {
        setError(error.message);
        setLoading(false);
      });
  }, []);

  if (loading) {
    return <div className="loading">加载中...</div>;
  }

  if (error) {
    return <div className="error">错误: {error}</div>;
  }

  return (
    <div className="schedule-list-container">
      <h1>排片列表</h1>
      <div className="schedule-table-container">
        <table className="schedule-table">
          <thead>
            <tr>
              <th>ID</th>
              <th>电影名称</th>
              <th>电影ID</th>
              <th>开始时间</th>
              <th>票价 (元)</th>
            </tr>
          </thead>
          <tbody>
            {schedules.map((schedule) => (
              <tr key={schedule.id}>
                <td>{schedule.id}</td>
                <td>{movies[schedule.movie_id] || "未知电影"}</td>
                <td>{schedule.movie_id}</td>
                <td>{new Date(schedule.start_time).toLocaleString()}</td>
                <td>{schedule.price.toFixed(2)}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}
